#pragma once
#include <functional>
#include <fcntl.h>
#include <memory>
#include "Log.hpp"
#include "Reactor.hpp"
#include "Common.hpp"

using handler_t = std::function<std::string (std::string& )>;

class Reactor;

class Connection{
public:
	// 统一行为接口
	virtual void Recever() = 0;
	virtual void Sender() = 0;
	virtual void Excepter() = 0;
	virtual int GetSockFd() = 0;

	Connection(): _events(), _owner(nullptr){}

	// 实现共性功能接口
	// 设置当前连接关注的事件
	void SetEvents(const uint32_t & events){
		_events = events;
	}

	uint32_t GetEvent(){
		return _events;
	}

	void SetOwner(Reactor* owner){
		_owner = owner;
	}

	Reactor* GetOwner(){
		return _owner;
	}

	void RegisterHandler(const handler_t & handler){
		_handler = handler;
	}

	void SetNoBlock(int sockfd){
		int flags = fcntl(sockfd, F_GETFL);
		if(flags < 0){
			LOG(LogLevel::ERROR) << "SetNoBlock fcntl F_GETFL error";
			return;
		}
		int ret = fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
		if(ret >= 0){
			LOG(LogLevel::DEBUG) << "SetNoBlock success";
		}
	}


private:
	uint32_t _events; // 存储关注的epoll事件
	
	// 回指指针，目的是让Connection能调用Reactor的方法
	Reactor* _owner; 

public:
	// 回调函数
	handler_t _handler;

};